import type {
  CreateCrudOptionsProps,
  CreateCrudOptionsRet,
  CrudExpose,
} from '@fast-crud/fast-crud';

import type { Ref } from 'vue';

import type { ExtendedModalApi } from '@vben/common-ui';
import type { Undefinedable } from '@vben/types';

import type { DefUserModel, FormRulesExt } from '#/api';
import type { ActionEnum } from '#/enums/commonEnum';

import { ref } from 'vue';

import { useAccess } from '@vben/access';
import { $t } from '@vben/locales';

import { DefUserApi } from '#/api/devOperation/tenant/defUser';
import { DictEnum } from '#/enums/commonEnum';
import { PermCode } from '#/enums/perm';
import {
  backendDict,
  createdTimeColumn,
  deleteButton,
  indexColumn,
  STATE_CONSTANT_DICT,
} from '#/plugins/fast-crud/common';
import { downloadByResponse } from '#/utils/file/download';

const { hasPermission } = useAccess();
const permCode = PermCode.devOperation.tenant.defUser;

type ContextRef = {
  restPasswordRef: Ref<Undefinedable<ExtendedModalApi>>;
};

export function createCrudOptions(
  props: CreateCrudOptionsProps<DefUserModel.DefUserResultVO, ContextRef>,
): CreateCrudOptionsRet<DefUserModel.DefUserResultVO> {
  const selectedRowKeys = ref<string[]>([]);

  return {
    crudOptions: {
      request: {
        pageRequest: DefUserApi.pageRequest,
        addRequest: DefUserApi.addRequest,
        editRequest: DefUserApi.editRequest,
        delRequest: DefUserApi.delRequest,
        infoRequest: DefUserApi.infoRequest,
      },
      actionbar: {
        buttons: {
          add: {
            show: hasPermission(permCode.add),
          },
          ...deleteButton({
            crudExpose: props.crudExpose,
            selectedRowKeys,
            role: permCode.delete,
            removeFn: DefUserApi.remove,
          }),
          export: {
            text: '导出',
            async click() {
              const response = await DefUserApi.exportFile({
                current: 1,
                size: 1000,
                model: { ...props.crudExpose.getSearchFormData() },
              });
              downloadByResponse(response);
            },
          },
        },
      },
      search: {
        col: { span: 6 },
      },
      table: {
        striped: true,
        rowKey: 'id',
        rowSelection: {
          type: 'checkbox',
          selectedRowKeys,
          onChange: (changed: string[]) => {
            selectedRowKeys.value = changed;
          },
        },
      },
      rowHandle: {
        width: '200px',
        buttons: {
          edit: {
            show: hasPermission(permCode.edit),
          },
          remove: {
            show: hasPermission(permCode.delete),
          },
          copy: {
            show: hasPermission(permCode.add),
          },
          reset: {
            show: hasPermission(permCode.resetPassword),
            dropdown: true,
            text: '重置密码',
            click: (context) => {
              props.context?.restPasswordRef.value?.setData({
                record: context.row,
              });
              props.context?.restPasswordRef.value?.open();
            },
          },
        },
      },
      form: {
        group: {
          type: 'tabs', // collapse, tabs
          // type: 'collapse', // collapse, tabs
          accordion: false, // 手风琴模式
          displayDirective: 'show',
          triggerAreas: ['arrow'],
          groups: {
            login: {
              header: '登录信息',
              columns: [
                'username',
                'email',
                'mobile',
                'idCard',
                'wxOpenId',
                'ddOpenId',
              ],
            },
            base: {
              header: '基础信息',
              columns: ['nickName', 'sex', 'state', 'workDescribe'],
            },
            other: {
              header: '额外信息',
              columns: [
                'passwordErrorLastTime',
                'passwordErrorNum',
                'passwordExpireTime',
                'lastLoginTime',
              ],
            },
          },
        },
      },
      columns: {
        ...indexColumn(props.crudExpose),
        username: {
          title: $t('devOperation.tenant.defUser.username'),
          type: 'text',
          search: { show: true },
        },
        email: {
          title: $t('devOperation.tenant.defUser.email'),
          type: 'text',
          search: { show: true },
        },
        mobile: {
          title: $t('devOperation.tenant.defUser.mobile'),
          type: 'text',
          search: { show: true },
        },
        idCard: {
          title: $t('devOperation.tenant.defUser.idCard'),
          type: 'text',
          search: { show: true },
        },
        wxOpenId: {
          title: $t('devOperation.tenant.defUser.wxOpenId'),
          type: 'text',
          form: { show: false },
          column: { show: false },
          viewForm: { show: true },
        },
        ddOpenId: {
          title: $t('devOperation.tenant.defUser.ddOpenId'),
          type: 'text',
          column: { show: false },
          form: { show: false },
          viewForm: { show: true },
        },
        nickName: {
          title: $t('devOperation.tenant.defUser.nickName'),
          type: 'text',
          search: { show: true },
          form: { col: { span: 24 } },
        },
        sex: {
          title: $t('devOperation.tenant.defUser.sex'),
          type: 'dict-radio',
          dict: backendDict(DictEnum.Sex),
        },
        state: {
          title: $t('devOperation.tenant.defUser.state'),
          type: 'dict-radio',
          dict: STATE_CONSTANT_DICT,
          addForm: { value: true },
        },
        workDescribe: {
          title: $t('devOperation.tenant.defUser.workDescribe'),
          type: 'textarea',
          column: { show: false },
          form: { col: { span: 24 } },
        },
        passwordErrorLastTime: {
          title: $t('devOperation.tenant.defUser.passwordErrorLastTime'),
          type: 'password',
          column: { show: false },
          viewForm: { show: true },
          form: {
            show: false,
            component: {
              format: 'YYYY-MM-DD HH:mm:ss',
              valueFormat: 'YYYY-MM-DD HH:mm:ss',
            },
          },
          valueBuilder({ value, row, key }) {
            if (value !== null && row) {
              row[key] = value;
            }
          },
        },
        passwordErrorNum: {
          title: $t('devOperation.tenant.defUser.passwordErrorNum'),
          type: 'password',
          viewForm: { show: true },
          form: { show: false },
          column: { show: false },
        },
        passwordExpireTime: {
          title: $t('devOperation.tenant.defUser.passwordExpireTime'),
          type: 'password',
          column: { show: false },
          viewForm: { show: true },
          form: {
            show: false,
            component: {
              format: 'YYYY-MM-DD HH:mm:ss',
              valueFormat: 'YYYY-MM-DD HH:mm:ss',
            },
          },
          valueBuilder({ value, row, key }) {
            if (value !== null && row) {
              row[key] = value;
            }
          },
        },
        lastLoginTime: {
          title: $t('devOperation.tenant.defUser.lastLoginTime'),
          type: 'datetime',
          column: { show: false },
          viewForm: { show: true },
          form: {
            show: false,
            component: {
              format: 'YYYY-MM-DD HH:mm:ss',
              valueFormat: 'YYYY-MM-DD HH:mm:ss',
            },
          },
          valueBuilder({ value, row, key }) {
            if (value !== null && row) {
              row[key] = value;
            }
          },
        },
        ...createdTimeColumn({}),
      },
    },
  };
}

export const frontRules = (
  _crudExpose: CrudExpose,
  _mode: ActionEnum,
): FormRulesExt => {
  return {};
};
